package Backend

import (
	"fmt"
	_ "github.com/astaxie/beego/cache/redis"
	"github.com/json-iterator/go"
	"github.com/syyongx/php2go"
	"hello/controllers/Base"
	"hello/models"
	"hello/wl"
	"hello/wl/service"

	"log"

	"sync"
	"time"
)

type UserController struct {
	Base.BaseController
}

var lock sync.Mutex


func  init()  {

}


func Count(ch chan string,zhi string) {
	ch <- zhi
	fmt.Println("写入携程")
}

func (this *UserController) Index() {
	jsoninfo := this.GetString(":id")
	fmt.Println(jsoninfo)




	this.AjaxSuccess(jsoninfo)
}

func liu()  {
	lock.Lock()

	lock.Unlock()

}
func redisLocok()  {
	lock.Lock()
	redis:=wl.WLRedis()
	Num,_:=redis.Get("count").Int()
	fmt.Println(Num)
	Num++
	redis.Set("count",wl.ToString(Num),10*60*time.Second)

	lock.Unlock()

}


func (this *UserController) Index2() {

	//counter=0
	var array []interface{}


	//WlWrite("1")
	//zhi:=WlRead()

	//fmt.Println(wl.ToInt(zhi))
	for i := 0; i < 10000; i++ {

		go redisLocok()
	}
	//waitgroup.Wait() //.Wait()这里会发生阻塞，直到队列中所有的任务结束就会解除阻塞


	//
	//for i:=0;i<10;i++  {
	//
	//	// 多个同时读
	//	 go tracefile(wl.ToString(i))
	//
	//}


	//go Count(ChA,"asdasd")
	//go Count(ChA,wl.Uniqid())

	this.AjaxSuccess(12)





	//for _, ch := range(ChA) {
	//	info:= <-ch
	//	fmt.Println(info)
	//	array = append(array, info)
	//}

	this.AjaxSuccess(array)
}



func (this *UserController) Index3() {



	this.AjaxSuccess(123123)
}

//用户信息
func (this *UserController) UserInfo() {
	id,_:= this.GetInt(":id")
	if php2go.Empty(id){
		this.AjaxError("错误请求!")
	}
	var user=models.UserShow{Id:id}

	user.FindById()

	fmt.Println(time.Second)

	this.AjaxSuccess(user)
}
//用户的文章
func (this *UserController)UserPost()  {
	id,_:= this.GetInt(":id")
	action:= this.GetString(":action")
	page,_:= this.GetInt("page",1)

	if php2go.Empty(id) || php2go.Empty(action){
		this.AjaxError("错误请求!")
	}
	var user=models.User{Id:id}

	var post  []models.Post
	var count int
	switch action {

	case "post"://用户的文章
		post,count=user.UserPosts(page,wl.Limit())

	case "zan"://用户赞的文章
		post,count=user.UserZanPosts(page,wl.Limit())

	case "comment"://用户评论的文章
		post,count=user.UserCommentPosts(page,wl.Limit())
	}

	this.AjaxSuccess(map[string]interface{}{"post":post,"count":count})
}

//用户信息
func (this *UserController) MyInfo() {
	user:=this.GetUser()
	this.AjaxSuccess(user)
}

//修改用户信息
func (this *UserController)UpdateUser(){
	user := models.User{Id:wl.ToInt(this.GetPost("id").(string)),
					Username:this.GetPost("username").(string),
					Tou:this.GetPost("tou").(string)}

	Base.Valid.Required(user.Username, "Username")
	Base.Valid.Required(user.Id, "Id")
	Base.Valid.Required(user.Tou, "Tou")
	if Base.Valid.HasErrors() {
		// 如果有错误信息，证明验证没通过 // 打印错误信息
		for _, err := range Base.Valid.Errors { log.Println(err.Key, err.Message) }
		this.AjaxError("参数错误!")
	}
	isok:=user.UpdateInfo()
	if isok {
		this.AjaxSuccess("修改成功!")
	}else{
		this.AjaxError("修改失败!")
	}
}

//关注某人+取消关注
func (this *UserController)FanAction(){
	user:=this.GetUser()
	fan := models.Fan{StarId:wl.ToInt(this.GetString(":id")),FanId:user.Id}

	Base.Valid.Required(fan.StarId, "StarId")
	if Base.Valid.HasErrors() {
		// 如果有错误信息，证明验证没通过 // 打印错误信息
		for _, err := range Base.Valid.Errors { log.Println(err.Key, err.Message) }
		this.AjaxError("参数错误!")
	}

	fan.IsFan()

	if php2go.Empty(fan.Id) {
		fan.CreatedFan()
		this.AjaxSuccess("关注成功!")
	}else{
		fan.DeleteFan()
		this.AjaxError("取消关注成功!")
	}

}
//粉丝和关注的人的个数
func (this *UserController)FansCount(){
	id,err:=this.GetInt(":id")
	if err!=nil {
		this.AjaxError("参数错误!")
	}
	user:=models.User{Id:id}
	fmt.Println(id,err,user)
	Base.Valid.Required(user.Id, "Id")
	if Base.Valid.HasErrors() {
		// 如果有错误信息，证明验证没通过 // 打印错误信息
		for _, err := range Base.Valid.Errors { log.Println(err.Key, err.Message) }
		this.AjaxError("参数错误!")
	}

	var fanCount,starCount int

	user.FanStarCount(&fanCount,&starCount)

	this.AjaxSuccess(map[string]int{"fans":fanCount,"star":starCount})
}
func (this *UserController)FanUsers()  {
	id,err:=this.GetInt(":id")
	action:=this.GetPost(":action")
	if err!=nil {
		this.AjaxError("参数错误!")
	}
	this.PageInit()


	var fanUsers []models.UserShow
	var starUsers []models.UserShow
	user:=models.User{Id:id}
	//我的粉丝
	if action=="fan"{
		user.FanUsers(&fanUsers,this.Page,this.Limit)
		this.AjaxSuccess(fanUsers)
	}else{
		user.StarUsers(&starUsers,this.Page,this.Limit)
		this.AjaxSuccess(starUsers)
	}



	
}
//是否关注
func (this *UserController)IsFan(){
	user:=this.GetUser()
	fan := models.Fan{StarId:wl.ToInt(this.GetString(":id")),FanId:user.Id}

	Base.Valid.Required(fan.StarId, "StarId")
	if Base.Valid.HasErrors() {
		// 如果有错误信息，证明验证没通过 // 打印错误信息
		for _, err := range Base.Valid.Errors { log.Println(err.Key, err.Message) }
		this.AjaxError("参数错误!")
	}

	fan.IsFan()

	if php2go.Empty(fan.Id) {

		this.AjaxSuccess(false)
	}else{

		this.AjaxSuccess(true)
	}

}




func (this *UserController) IndexPost() {
	jsoninfo := this.GetString("name")

	this.Data["json"] =jsoninfo

	this.ServeJSON()
}

//用户登录
func (this *UserController) UserLogin() {
	email := this.GetPost("email")
	password := this.GetPost("password")


	fmt.Println("邮箱",email,"密码",password)
	if php2go.Empty(email) ||  php2go.Empty(password){
		this.AjaxError("请输入账号密码")
	}

	message:=service.UserLogin(email,password)

	if message.Status==false{
		this.AjaxError(message.Message)
	}else{
		this.AjaxSuccess(message.Message)
	}

}

/**
检查登录
登录返回用户结构信息
没有返回 code=0
 */
func (this * UserController) CheckLogin() {

	token:=this.GetPost("token")
	if php2go.Empty(token) {
		this.AjaxError("未登陆!")
	}

	byteValue := wl.RedisGet(token.(string))


	var  jsonUser models.User
	if err := jsoniter.Unmarshal(byteValue, &jsonUser); err != nil{
		fmt.Println("错误!error: ", err)
	}

	if php2go.Empty(jsonUser) {
		this.AjaxError("未登陆")
	}else{
		this.AjaxSuccess(jsonUser)
	}
}




// @router /read [get]
func (this *UserController) Read() {
	redisClient:=wl.WLRedis()

	userByteVal,_ := redisClient.Get("5cb9d2e1a65b4").Bytes()

	var user models.User

	if err := jsoniter.Unmarshal(userByteVal, &user); err != nil{
		fmt.Println("错误!error: ", err)
	}
	var testNull interface{}

	fmt.Println(php2go.Empty(testNull))
	this.AjaxSuccess(user)

}

/**
用户注册
 */
func (this *UserController) UserRegister()()  {
	username := this.GetString("username")
	password := this.GetString("password")
	email := this.GetString("email")


	salt:=php2go.Uniqid("")

	user := models.User{Email:email}

	user.FindByEmail()

	fmt.Println(user)
	if !php2go.Empty(user.Id) {
		this.AjaxError("账号已经存在!")
	}else{
			var users models.User
			users.Username = username
			users.Password = wl.WlSha256(password + salt)
			users.Salt = salt
			users.Email =email
			users.Tou = "default"

			users.Access_token = wl.WlSha256(php2go.Uniqid(""))

			users.CreateUser()

			if users.Id != 0 {
				this.AjaxSuccess("注册成功!")
			} else {
				this.AjaxError("注册失败!")
			}

		}

	this.ServeJSON()
}

func (this *UserController)UserInfoA()  {
	this.Test()
	this.AjaxSuccess(123)
}



